﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TWS.Cart.Business;
using TWS.Cart.Data;

public partial class Application_Cart_Administration_CategoryForm : System.Web.UI.Page
{
	int updateId = -1;

    protected void Page_Load(object sender, EventArgs e)
    {
		if (!String.IsNullOrEmpty(Request.QueryString["Id"]))
			updateId = Convert.ToInt32(Request.QueryString["Id"]);

		if (!IsPostBack)
		{
			//Construct DDL
			CartCatCategoryCollection cat = new CartCatCategoryCollection()
			.OrderByAsc(CartCatCategory.Columns.Name)
			.Load();

			DropDownListParentId.Items.Add(new ListItem("Select Parent","0"));

			foreach (var c in cat)
				DropDownListParentId.Items.Add(new ListItem(c.Name, c.Id.ToString()));

			//IF edit load data.
			if (updateId != -1)
			{
				CartCatCategory cData = CartCatCategory.FetchByID(updateId);

				DropDownListParentId.SelectedValue = cData.ParentCategoryId.ToString();
				TextBoxName.Text = cData.Name;
				TextBoxDescription.Text = cData.Description;
				TextBoxOrder.Text = cData.CategoryOrder.ToString();
			}

		}
    }

	protected void ButtonNew_Click(object sender, EventArgs e)
	{
		CartCatCategory c;

		//Select if this is an update or a new register.
		if (updateId == -1)//Its a new record
			c = new CartCatCategory();
		else//We are updating
			c = CartCatCategory.FetchByID(updateId);

		c.ParentCategoryId = Convert.ToInt32(DropDownListParentId.SelectedValue);
		c.Name = TextBoxName.Text;
		c.Description = TextBoxDescription.Text;
		c.CategoryOrder = Convert.ToInt32(TextBoxOrder.Text);

		try
		{
			c.Save();
			
			if (updateId == -1)
				MessageB01.Text = "Record inserted.";
			else
				MessageB01.Text = "Record updated.";

			MessageB01.Visible = true;
		}
		catch (Exception ex)
		{
			MessageB01.Text = "An Error Ocurred";
			MessageB01.Visible = true;
		}
	}
}
